package com.caigou.modules.forum.ui.rank

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.GiftRankItemAdapter
import com.caigou.modules.forum.bean.PostRankItemBean
import com.caigou.modules.forum.databinding.ActivityGiftRankBinding
import com.caigou.modules.forum.viewmodel.RankViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2022/02/24
 */
@Route(path = RouterPath.Forum.PAGE_GIFT_RANK)
@AndroidEntryPoint
class GiftRankActivity : BaseActivity() {

    private lateinit var binding: ActivityGiftRankBinding
    private val rankViewModel: RankViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.USER_ID)
    var userId = ""

    private val headerList = mutableListOf<PostRankItemBean>()

    private val mAdapter: GiftRankItemAdapter by lazy {
        GiftRankItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGiftRankBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.giftRankLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.giftRankSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchGiftRankList()
            }
        }

        binding.giftRankRecyclerView.run {
            layoutManager = LinearLayoutManager(this@GiftRankActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@GiftRankActivity))
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.item_gift_rank_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.senderUserId)
                        .navigation()
                }
                R.id.item_gift_rank_btn_follow -> {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, item.senderUserId)
                }
            }
        }

        binding.giftRankTvBack.setOnClickListener {
            finish()
        }

        fetchGiftRankList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(rankViewModel.giftRankListLiveData, ::handleGetGiftRankList)
        observe(followViewModel.followLiveData, ::handleSetFollow)
    }

    private fun handleGetGiftRankList(result: Resource<MutableList<PostRankItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.giftRankSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取礼物榜信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.giftRankSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }

                headerList.clear()
                val tempList = mutableListOf<PostRankItemBean>()
                for (index in 0 until result.data!!.size) {
                    if (index <= 2) {
                        headerList.add(result.data!![index])
                    } else {
                        tempList.add(result.data!![index])
                    }
                }
                mAdapter.setList(tempList)
                handleLadder()
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                fetchGiftRankList()
            }
        }
    }

    private fun handleLadder() {
        when (headerList.size) {
            1 -> {
                binding.giftRankLayoutLadder.ladderTvNickname1.text = headerList[0].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum1.text = headerList[0].charmValue.toString()
                if (TextUtils.isEmpty(headerList[0].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[0].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.giftRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].senderUserId)
                }
            }
            2 -> {
                binding.giftRankLayoutLadder.ladderTvNickname1.text = headerList[0].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum1.text = headerList[0].charmValue.toString()
                if (TextUtils.isEmpty(headerList[0].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[0].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.giftRankLayoutLadder.ladderTvNickname2.text = headerList[1].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum2.text = headerList[1].charmValue.toString()
                if (TextUtils.isEmpty(headerList[1].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[1].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[1].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.giftRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].senderUserId)
                }

                binding.giftRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].senderUserId)
                }
            }
            3 -> {
                binding.giftRankLayoutLadder.ladderTvNickname1.text = headerList[0].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum1.text = headerList[0].charmValue.toString()
                if (TextUtils.isEmpty(headerList[0].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[0].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.giftRankLayoutLadder.ladderTvNickname2.text = headerList[1].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum2.text = headerList[1].charmValue.toString()
                if (TextUtils.isEmpty(headerList[1].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[1].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[1].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.giftRankLayoutLadder.ladderTvNickname3.text = headerList[2].senderUserNickName
                binding.giftRankLayoutLadder.ladderTvNum3.text = headerList[2].charmValue.toString()
                if (TextUtils.isEmpty(headerList[2].senderUserHeadImg)) {
                    binding.giftRankLayoutLadder.ladderIvAvatar3.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this, headerList[2].senderUserHeadImg, binding.giftRankLayoutLadder.ladderIvAvatar3)
                }
                if (headerList[2].concern) {
                    binding.giftRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.giftRankLayoutLadder.ladderBtnFollow3.text = "已关注"
                } else {
                    binding.giftRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.giftRankLayoutLadder.ladderBtnFollow3.text = "+关注"
                }


                binding.giftRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderIvAvatar3.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[2].senderUserId)
                        .navigation()
                }

                binding.giftRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].senderUserId)
                }

                binding.giftRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].senderUserId)
                }

                binding.giftRankLayoutLadder.ladderBtnFollow3.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[2].senderUserId)
                }
            }
        }
    }


    private fun fetchGiftRankList() {
        val currentUserId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        rankViewModel.getGiftRankList(userId, currentUserId)
    }
}